from django.contrib.auth import login
from django.db import DatabaseError
from django.shortcuts import render
from django.urls import reverse
from django.views import View
from django.http import HttpResponseForbidden, HttpResponse, JsonResponse
import re
from django.shortcuts import redirect

from .models import User
from meiduomall_front.utils.response_code import RETCODE

# Create your views here.

class RegisterView(View):
    """用户注册"""
    def get(self, request):
        return render(request, 'register.html')


    def post(self, request):
        """表单登陆"""
        username = request.POST.get("username")
        password = request.POST.get("password")
        password2 = request.POST.get("password2")
        mobile = request.POST.get("mobile")
        allow = request.POST.get("allow")
        # 判断参数是否齐全
        if not all([username, password, password2, mobile, allow]):
            return HttpResponseForbidden("缺少必传参数")
        # 判断用户名是否正确
        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$", username):
            return HttpResponseForbidden("请输入5-20个字符的用户名")
        # 判断密码是否正确并校验两次密码是否一致
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return HttpResponseForbidden("请输入8-20位的密码")
        if password != password2:
            return HttpResponseForbidden("两次输入的密码不一致")
        # 判断手机号是否正确
        if not re.match(r'^1[3-9]\d{9}', mobile):
            return HttpResponseForbidden("请输入正确的手机号码")
        # 判断是否勾选协议
        if allow != 'on':
            return HttpResponseForbidden("请先勾选协议")

        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, "register.html", {"register_errmsg": "注册失败"})

        # 状态保持
        login(request, user)

        # return HttpResponse("注册成功，重新回到首页")
        return redirect(reverse("contents:index"))

class UsernameCountView(View):
    """用户名重复验证"""
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({"code": RETCODE.OK, 'errmsg': 'OK', 'count': count})

class MobileCountView(View):
    """手机号重复注册"""
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({"code": RETCODE.OK, 'errmsg': 'OK', 'count': count})